package com.mall.b2c.controller;

import com.mall.common.service.MailService;
import com.mall.common.util.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.mall.b2c.Setting;
import com.mall.b2c.util.SettingUtils;
import com.mall.common.controller.BaseController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/admin/b2c/setting")
public class SettingController extends BaseController {

	@Resource
	private MailService mailService;

	@RequestMapping("edit")
	public String edit(Model model) {
		model.addAttribute("setting", SettingUtils.get());
		return "/admin/b2c/setting/edit";
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public String update(Setting setting, RedirectAttributes redirectAttributes) throws Exception {
		Setting persistent = SettingUtils.get();
	
		if (setting.getIsAdminLoginFailureLock() == false) {
			setting.setAdminLoginFailureLockCount(3);
			setting.setAdminLoginFailureLockTime(10);
		}
		BeanUtils.copyProperties(setting, persistent);
		SettingUtils.set(persistent);
		redirect(redirectAttributes, successMessage);
		return "redirect:edit.jhtml";
	}


	/**
	 * 发送测试邮件
	 * @param smtpFromMail
	 * @param smtpHost
	 * @param smtpPort
	 * @param smtpUsername
	 * @param smtpPassword
	 * @param toMail
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/mailTest",method=RequestMethod.POST)
	public String mailTest(String smtpFromMail, String smtpHost, String smtpPort,
						   String smtpUsername, String smtpPassword, String toMail, HttpServletResponse response){
		Boolean flag = mailService.sendTestMail(smtpFromMail, smtpHost, smtpPort, smtpUsername, smtpPassword, toMail);
		return ResponseUtils.renderJSON(flag ? successMessage : errorMessage, response);
	}
}
